package com.ruoyi.system.service.impl;

import com.ruoyi.system.domain.ExamItems;
import com.ruoyi.system.domain.ExamResult;
import com.ruoyi.system.domain.ExamScore;
import com.ruoyi.system.domain.ExamScoreDetail;
import com.ruoyi.system.mapper.ExamItemsMapper;
import com.ruoyi.system.mapper.ExamScoreDetailMapper;
import com.ruoyi.system.mapper.ExamScoreMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created with IntelliJ IDEA.
 * User: samsung
 * Date: 2019/9/14
 * Time: 21:52
 * Description:计算分数类。
 */@Component
public class CalcScore {
     @Autowired
     private ExamItemsMapper examItemsMapper;
     @Autowired
     private ExamScoreMapper examScoreMapper;
     @Autowired
     private ExamScoreDetailMapper examScoreDetailMapper;

     //计算分数的方法。
     public ExamResult getScore(ExamResult data, int paperid, long userid){
         AtomicInteger total = new AtomicInteger(); //用于存总分。
         AtomicInteger rights = new AtomicInteger(); //答对题目数。
         AtomicInteger errors = new AtomicInteger(); //答错题目数。

        //查出所有题目的正确答案。
         List<ExamItems> examItemsList = examItemsMapper.searchItems(paperid);

         //比对答案，计算得分。
         List<ExamScoreDetail> resultList = data.getResultList();
         resultList.forEach(examScoreDetail -> {
             long eid = examScoreDetail.getEid();
             Optional<ExamItems> any = examItemsList.stream()
                     .filter(examItems -> examItems.getEid() == eid)
                     .findAny();
             if(any.isPresent()){
                 ExamItems examItems = any.get();
                 String ekeys = examItems.getEkeys();
                 examScoreDetail.setRanswer(ekeys);
                 if(ekeys.equals(examScoreDetail.getUanswer())){
                     Integer escore = examItems.getEscore();
                     total.addAndGet(escore);
                     examScoreDetail.setUpoint(escore);
                     rights.getAndIncrement();
                 }else {
                     errors.getAndIncrement();
                     examScoreDetail.setUpoint(0);
                 }

             }
         });

        //将成绩存入数据库中。
         ExamScore examScore = new ExamScore();
            examScore.setPaperid(paperid);
            examScore.setUserid(userid);
            examScore.setScore(total.get());
            examScore.setRights(rights.get());
            examScore.setErrors(errors.get());
         examScoreMapper.insertSelective(examScore);


         //遍历设置成绩的id，
        for (int i = 0; i<resultList.size();i++){
            //遍历设置成绩id
            resultList.get(i).setScoreid(examScore.getScoreid());
        }

        //将成绩详情集合存到数据库中
         examScoreDetailMapper.insertExamScoreDetailsByList(resultList);
         data.setExamScore(examScore);
         return data;
     }
}
